import router from '@/router'
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex)

function addNewRoute (menuList) {
  const routes = router.options.routes
  console.log('打印当前路由')
  console.log(routes)

  routes.forEach(routeItem => {
    if (routeItem.path === '/home') {
      menuList.forEach(menu => {
        const childrenRoute = {
          path: menu.url,
          name: menu.menuName,
          component: () => import('../views/' + menu.menuComponent)
        }
        // if (menu.url === '/document') {
        //   const documentchildren = {
        //     path: menu.url,
        //     name: menu.menuName,
        //     component: () => import('../views/' + menu.menuComponent)
        //   }
        //   menu.children().push(documentchildren)
        // }
        routeItem.children.push(childrenRoute)
      })
      // resetRouter()
      router.addRoute(routeItem)
    }
  })
}

export default new Vuex.Store({
  state: {
    token: sessionStorage.getItem('token'),
    userInfo: '',
    menu: []
  },
  getters: {
    getUser: state => {
      return state.userInfo
    },
    getToken: state => {
      if (state.token == null) {
        return ''
      } else {
        return state.token
      }
    },
    getMenu (state) {
      return state.menu
    }
  },
  mutations: {
    SET_Token: (state, token) => {
      state.token = token
      sessionStorage.setItem('token', token)
    },
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo
      sessionStorage.setItem('user', JSON.stringify(userInfo))
    },
    REMOVE_INFO: (state) => {
      state.token = ''
      state.userInfo = {}
      sessionStorage.setItem('token', '')
      sessionStorage.setItem('user', JSON.stringify(''))
    },
    setMenu (state, menuList) {
      state.menu = menuList
      addNewRoute(menuList)
    },
    setRouter (state, menuList) {
      addNewRoute(menuList)
    }
  },
  actions: {
  },
  modules: {
  },
  plugins: [createPersistedState]
})
